<template>
  <div class="payable-summary">
    <!-- 筛选区 -->
    <el-form :model="filter" inline class="filter-bar">
      <!-- 日期范围 -->
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="filter.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <!-- 汇总依据 -->
      <el-form-item label="汇总依据">
        <el-select v-model="filter.summaryBy" placeholder="请选择">
          <el-option label="供应商" value="supplier" />
          <el-option label="供应商类别" value="category" />
          <el-option label="业务员" value="salesman" />
        </el-select>
      </el-form-item>

      <!-- 供应商选择（弹窗） -->
      <el-form-item label="供应商">
        <el-button type="primary" @click="openDialog('supplier')">
          {{ selectedSupplier.label || "请选择供应商" }}
        </el-button>
      </el-form-item>

      <!-- 供应商类别选择（树弹窗） -->
      <el-form-item label="供应商类别">
        <el-button type="primary" @click="openDialog('category')">
          {{ selectedCategory.label || "请选择类别" }}
        </el-button>
      </el-form-item>

      <!-- 业务员选择（弹窗） -->
      <el-form-item label="业务员">
        <el-button type="primary" @click="openDialog('salesman')">
          {{ selectedSalesman.label || "请选择业务员" }}
        </el-button>
      </el-form-item>

      <!-- 筛选复选框 -->
      <el-form-item>
        <el-checkbox v-model="filter.hideZero">余额为0不显示</el-checkbox>
        <el-checkbox v-model="filter.hideNoTrans">无发生额不显示</el-checkbox>
        <el-checkbox v-model="filter.hideZeroAndNoTrans"
          >余额为0且无发生额不显示</el-checkbox
        >
        <el-checkbox v-model="filter.showDisabled">显示禁用供应商</el-checkbox>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="info" @click="resetFilter">重置</el-button>
        <el-button type="primary" @click="queryData">查询</el-button>
        <el-button type="success" @click="exportData">导出</el-button>
        <el-button type="info" @click="printData">打印</el-button>
      </el-form-item>
    </el-form>

    <!-- ========== 供应商选择弹窗 ========== -->
    <el-dialog
      title="选择供应商"
      v-model="dialogs.supplier.visible"
      width="720px"
    >
      <div class="dialog-header">
        <el-input
          v-model="dialogs.supplier.keyword"
          placeholder="输入编号/名称"
          clearable
          style="width: 240px"
        />
        <el-checkbox v-model="dialogs.supplier.showDisabled" class="ml-4"
          >显示禁用供应商</el-checkbox
        >
        <el-button type="primary" class="ml-4" @click="fetchSuppliers"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.supplier.list"
        :row-key="(row) => row.id"
        @selection-change="handleSupplierSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="编号" min-width="120" sortable />
        <el-table-column prop="name" label="名称" min-width="180" sortable />
        <el-table-column prop="category" label="类别" min-width="120" />
        <el-table-column
          prop="initialPayable"
          label="期初应付款"
          align="right"
          min-width="140"
          sortable
        />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.supplier.limit = val)"
        @current-change="(val) => (dialogs.supplier.page = val)"
        :current-page="dialogs.supplier.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.supplier.limit"
        :total="dialogs.supplier.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.supplier.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('supplier')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 供应商类别选择弹窗（树结构） ========== -->
    <el-dialog
      title="选择供应商类别"
      v-model="dialogs.category.visible"
      width="360px"
    >
      <el-tree
        ref="categoryTreeRef"
        :data="categoryTree"
        show-checkbox
        node-key="id"
        :props="{ label: 'label', children: 'children' }"
        @check="handleCategoryCheck"
        default-expand-all
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.category.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('category')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 业务员选择弹窗 ========== -->
    <el-dialog
      title="选择业务员"
      v-model="dialogs.salesman.visible"
      width="540px"
    >
      <div class="dialog-header">
        <el-input
          v-model="dialogs.salesman.keyword"
          placeholder="输入编号/名称"
          clearable
          style="width: 240px"
        />
        <el-checkbox v-model="dialogs.salesman.showDisabled" class="ml-4"
          >显示禁用人员</el-checkbox
        >
        <el-button type="primary" class="ml-4" @click="fetchSalesmen"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.salesman.list"
        :row-key="(row) => row.id"
        @selection-change="handleSalesmanSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="编号" min-width="120" sortable />
        <el-table-column prop="name" label="名称" min-width="180" sortable />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.salesman.limit = val)"
        @current-change="(val) => (dialogs.salesman.page = val)"
        :current-page="dialogs.salesman.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.salesman.limit"
        :total="dialogs.salesman.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.salesman.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('salesman')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 应付账款表格 ========== -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      show-summary
      :summary-method="generateSummary"
      :header-cell-style="{ background: '#F8F9FA' }"
    >
      <el-table-column
        prop="category"
        label="供应商类别"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="code"
        label="供应商编号"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="name"
        label="供应商名称"
        min-width="180"
        sortable
      />
      <el-table-column
        prop="initialBalance"
        label="期初余额"
        align="right"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="currentPayable"
        label="本期应付"
        align="right"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="currentPayment"
        label="本期付款"
        align="right"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="endBalance"
        label="期末余额"
        align="right"
        min-width="120"
        sortable
      />
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

// ========== 筛选条件 ==========
const filter = reactive({
  dateRange: [new Date("2025/06/01"), new Date("2025/06/26")],
  summaryBy: "supplier", // 汇总依据：supplier/category/salesman
  supplier: [], // 选中的供应商
  category: [], // 选中的类别
  salesman: [], // 选中的业务员
  hideZero: false, // 余额为0不显示
  hideNoTrans: false, // 无发生额不显示
  hideZeroAndNoTrans: false, // 余额为0且无发生额不显示
  showDisabled: false, // 显示禁用供应商
});

// ========== 选中项回显 ==========
const selectedSupplier = ref({ label: "" });
const selectedCategory = ref({ label: "" });
const selectedSalesman = ref({ label: "" });

// ========== 对话框状态 ==========
const dialogs = reactive({
  supplier: {
    visible: false,
    keyword: "",
    showDisabled: false,
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    selected: [], // 选中的供应商行
  },
  category: {
    visible: false,
    selected: [], // 选中的树节点
    treeRef: ref(null), // 树形组件引用
  },
  salesman: {
    visible: false,
    keyword: "",
    showDisabled: false,
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    selected: [], // 选中的业务员行
  },
});

// ========== 基础数据模拟 ==========
// 供应商类别树（示例）
const categoryTree = ref([
  {
    id: 1,
    label: "广东",
    children: [
      { id: 11, label: "海鲜供应商" },
      { id: 12, label: "酒水饮料供应商" },
      { id: 13, label: "食品供应商" },
      { id: 14, label: "测试" },
    ],
  },
  {
    id: 2,
    label: "湖南",
    children: [
      { id: 21, label: "辣条供应商" },
      { id: 22, label: "零食供应商" },
    ],
  },
]);

// 模拟供应商列表
const mockSuppliers = [
  {
    id: 1,
    code: "G00001",
    name: "商品综合批发有限公司",
    category: "广东",
    initialPayable: 13881.78,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 13881.78,
  },
  {
    id: 2,
    code: "G00002",
    name: "金小蜂食品贸易有限公司",
    category: "酒水饮料供应商",
    initialPayable: 16446.44,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 16446.44,
  },
  {
    id: 3,
    code: "G00003",
    name: "广州食品批发有限公司",
    category: "食品供应商",
    initialPayable: 9555.65,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 9555.65,
  },
  {
    id: 4,
    code: "G00004",
    name: "深圳食品加工有限公司",
    category: "食品供应商",
    initialPayable: 16698.12,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 16698.12,
  },
  {
    id: 5,
    code: "G00005",
    name: "食品零售供应商",
    category: "广东",
    initialPayable: 12634.7,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 12634.7,
  },
  {
    id: 6,
    code: "G00007",
    name: "测试供应商",
    category: "",
    initialPayable: 116.0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 116.0,
  },
  {
    id: 7,
    code: "G00008",
    name: "测试",
    category: "",
    initialPayable: 200.0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 200.0,
  },
  {
    id: 8,
    code: "T001",
    name: "临时供应商",
    category: "",
    initialPayable: 678.0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 678.0,
  },
  {
    id: 9,
    code: "zhongtong",
    name: "中通快递",
    category: "",
    initialPayable: 0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 0,
  },
  {
    id: 10,
    code: "yunda",
    name: "韵达快递",
    category: "",
    initialPayable: 0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 0,
  },
  {
    id: 11,
    code: "yuantong",
    name: "圆通速递",
    category: "",
    initialPayable: 0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 0,
  },
  {
    id: 12,
    code: "sxjdfreight",
    name: "顺心",
    category: "",
    initialPayable: 0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 0,
  },
  {
    id: 13,
    code: "ems",
    name: "EMS",
    category: "",
    initialPayable: 0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 0,
  },
  {
    id: 14,
    code: "G00009",
    name: "测试111",
    category: "",
    initialPayable: 0,
    currentPayable: 0,
    currentPayment: 0,
    endBalance: 0,
  },
];

// 模拟业务员列表
const mockSalesmen = [
  { id: 1, code: "S001", name: "业务员A" },
  { id: 2, code: "S002", name: "业务员B" },
  { id: 3, code: "S003", name: "业务员C" },
];

// ========== 对话框交互逻辑 ==========
/** 打开对话框 */
const openDialog = (type) => {
  dialogs[type].visible = true;
  if (type === "supplier") fetchSuppliers();
  if (type === "salesman") fetchSalesmen();
};

/** 获取供应商列表（模拟） */
const fetchSuppliers = () => {
  const { keyword, showDisabled, page, limit } = dialogs.supplier;
  let filtered = mockSuppliers.filter(
    (item) => item.code.includes(keyword) || item.name.includes(keyword)
  );
  if (!showDisabled) {
    filtered = filtered.filter((item) => !item.disabled); // 模拟禁用逻辑
  }
  // 模拟分页
  const start = (page - 1) * limit;
  const end = start + limit;
  dialogs.supplier.list = filtered.slice(start, end);
  dialogs.supplier.total = filtered.length;
};

/** 获取业务员列表（模拟） */
const fetchSalesmen = () => {
  const { keyword, showDisabled, page, limit } = dialogs.salesman;
  let filtered = mockSalesmen.filter(
    (item) => item.code.includes(keyword) || item.name.includes(keyword)
  );
  if (!showDisabled) {
    filtered = filtered.filter((item) => !item.disabled); // 模拟禁用逻辑
  }
  // 模拟分页
  const start = (page - 1) * limit;
  const end = start + limit;
  dialogs.salesman.list = filtered.slice(start, end);
  dialogs.salesman.total = filtered.length;
};

/** 供应商选择事件 */
const handleSupplierSelect = (val) => {
  dialogs.supplier.selected = val;
};

/** 业务员选择事件 */
const handleSalesmanSelect = (val) => {
  dialogs.salesman.selected = val;
};

/** 类别选择事件（树） */
const handleCategoryCheck = (val) => {
  dialogs.category.selected = val;
};

/** 确认选择 */
const confirmSelection = (type) => {
  let label = "";
  if (type === "supplier") {
    if (dialogs.supplier.selected.length === 0) {
      ElMessage.warning("请选择供应商");
      return;
    }
    label = dialogs.supplier.selected.map((item) => item.name).join("、");
    filter.supplier = dialogs.supplier.selected;
  } else if (type === "category") {
    // 安全获取树形组件选中节点
    const checkedNodes =
      dialogs.category.treeRef.value?.getCheckedNodes() || [];
    if (checkedNodes.length === 0) {
      ElMessage.warning("请选择类别");
      return;
    }
    label = checkedNodes.map((node) => node.label).join("、");
    filter.category = checkedNodes;
  } else if (type === "salesman") {
    if (dialogs.salesman.selected.length === 0) {
      ElMessage.warning("请选择业务员");
      return;
    }
    label = dialogs.salesman.selected.map((item) => item.name).join("、");
    filter.salesman = dialogs.salesman.selected;
  }

  // 更新回显
  if (type === "supplier") selectedSupplier.value.label = label;
  if (type === "category") selectedCategory.value.label = label;
  if (type === "salesman") selectedSalesman.value.label = label;

  // 关闭对话框
  dialogs[type].visible = false;
  ElMessage.success("选择成功！");
};

/** 重置筛选 */
const resetFilter = () => {
  filter.dateRange = [new Date("2025/06/01"), new Date("2025/06/26")];
  filter.summaryBy = "supplier";
  filter.supplier = [];
  filter.category = [];
  filter.salesman = [];
  filter.hideZero = false;
  filter.hideNoTrans = false;
  filter.hideZeroAndNoTrans = false;
  filter.showDisabled = false;
  selectedSupplier.value.label = "";
  selectedCategory.value.label = "";
  selectedSalesman.value.label = "";
  ElMessage.success("筛选条件已重置");
};

// ========== 表格数据逻辑 ==========
const tableData = ref([]);

/** 查询数据（模拟） */
const queryData = () => {
  // 1. 筛选供应商（模拟逻辑）
  let filteredSuppliers = mockSuppliers;

  // 按类别过滤
  if (filter.category.length > 0) {
    filteredSuppliers = filteredSuppliers.filter((item) =>
      filter.category.some((cat) => item.category.includes(cat.label))
    );
  }

  // 按选中供应商过滤
  if (filter.supplier.length > 0) {
    filteredSuppliers = filteredSuppliers.filter((item) =>
      filter.supplier.some((s) => s.id === item.id)
    );
  }

  // 余额/发生额过滤
  if (filter.hideZero) {
    filteredSuppliers = filteredSuppliers.filter((item) => item.endBalance > 0);
  }
  if (filter.hideNoTrans) {
    filteredSuppliers = filteredSuppliers.filter(
      (item) => item.currentPayable !== 0 || item.currentPayment !== 0
    );
  }
  if (filter.hideZeroAndNoTrans) {
    filteredSuppliers = filteredSuppliers.filter(
      (item) =>
        !(
          item.endBalance === 0 &&
          item.currentPayable === 0 &&
          item.currentPayment === 0
        )
    );
  }

  // 2. 构建表格数据（根据汇总依据扩展）
  const result = [];
  filteredSuppliers.forEach((supplier) => {
    result.push({
      category: supplier.category,
      code: supplier.code,
      name: supplier.name,
      initialBalance: supplier.initialPayable,
      currentPayable: supplier.currentPayable,
      currentPayment: supplier.currentPayment,
      endBalance: supplier.endBalance,
    });
  });
  tableData.value = result;
};

/** 合计行计算 */
const generateSummary = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (["initialBalance", "endBalance"].includes(column.prop)) {
      const total = data.reduce((acc, item) => acc + item[column.prop], 0);
      sums[index] = total.toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

/** 导出（模拟） */
const exportData = () => {
  ElMessage.info("模拟导出...");
};

/** 打印（模拟） */
const printData = () => {
  ElMessage.info("模拟打印...");
};

// ========== 初始化 ==========
onMounted(() => {
  queryData(); // 初始加载数据
});
</script>

<style scoped>
.payable-summary {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

/* 合计行样式 */
.el-table__footer-row td {
  background-color: #fff2cc !important;
  font-weight: 500;
}

/* 表头样式 */
.el-table th {
  text-align: center;
}
</style>